package cnblogs.guzb.multiredis;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 顾志兵
 * @mail ipiger@163.com
 * @since 2024-03-22
 */
@Configuration
public class RedisConfiguration {
    @Primary
    @Bean("redis-connection-factory-db0")
    public RedisConnectionFactory createLettuceConnectionFactory0() {
        RedisStandaloneConfiguration clientProps = new RedisStandaloneConfiguration();
        clientProps.setHostName("localhost");
        clientProps.setPort(6379);
        clientProps.setDatabase(0);
        return new LettuceConnectionFactory(clientProps);
    }

    @Bean("redis-connection-factory-db1")
    public RedisConnectionFactory createLettuceConnectionFactory1() {
        RedisStandaloneConfiguration clientProps = new RedisStandaloneConfiguration();
        clientProps.setHostName("localhost");
        clientProps.setPort(6379);
        clientProps.setDatabase(1);
        return new LettuceConnectionFactory(clientProps);
    }

    @Primary
    @Bean("redis-template-db-0")
    public RedisTemplate<String, String> createRedisTemplate0(
            @Qualifier("redis-connection-factory-db0") RedisConnectionFactory factory0) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory0);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Bean("redis-template-db-1")
    public RedisTemplate<String, String> createRedisTemplate1(
            @Qualifier("redis-connection-factory-db1") RedisConnectionFactory factory1) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory1);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

}
